package com.qixiaobao.insure.service.impl;

import com.qixiaobao.common.config.SupplyConfig;
import com.qixiaobao.common.exception.UtilException;
import com.qixiaobao.common.utils.StringUtils;
import com.qixiaobao.common.utils.file.FileUtils;
import com.qixiaobao.common.utils.oss.OssUtil;
import com.qixiaobao.common.utils.pdf.PdfCoverUtils;
import com.qixiaobao.common.utils.pdf.PdfWaterUtils;
import com.qixiaobao.common.utils.uuid.IdUtils;
import com.qixiaobao.common.core.domain.entity.InsureFileCoverRule;
import com.qixiaobao.common.core.domain.entity.OverArea;
import com.qixiaobao.insure.domain.dto.InsureFileCoverRuleDTO;
import com.qixiaobao.insure.mapper.InsureFileCoverRuleMapper;
import com.qixiaobao.insure.service.IInsureFileCoverRuleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Description 保单遮盖处理  业务层处理
 * @Author yangxm
 * @Date 2025/7/10 10:05
 */
@Slf4j
@Service
public class InsureFileCoverRuleServiceImpl implements IInsureFileCoverRuleService {

    @Autowired
    private InsureFileCoverRuleMapper insureFileCoverRuleMapper;

    /**
     * 查询保单遮盖处理列表
     *
     * @param insureFileCoverRuleDTO
     * @return
     */
    @Override
    public List<InsureFileCoverRule> selectInsureFileCoverRuleList(InsureFileCoverRuleDTO insureFileCoverRuleDTO) {
        List<InsureFileCoverRule> list = insureFileCoverRuleMapper.selectInsureFileCoverRuleList(insureFileCoverRuleDTO);
        if (StringUtils.isNotEmpty(list)){
            for(InsureFileCoverRule rule : list){
                if ("1".equals(rule.getCoverDirection())){
                    rule.setCoverDirectionVal("上");
                } else if ("2".equals(rule.getCoverDirection())) {
                    rule.setCoverDirectionVal("下");
                } else if ("3".equals(rule.getCoverDirection())) {
                    rule.setCoverDirectionVal("左");
                } else if ("4".equals(rule.getCoverDirection())) {
                    rule.setCoverDirectionVal("右");
                }
            }
        }
        return list;
    }

    /**
     * 校验关键字是否唯一
     *
     * @param keyword
     * @param supplyName
     * @return
     */
    @Override
    public boolean checkKeywordUnique(String keyword, String supplyName) {
        int count = insureFileCoverRuleMapper.selectInsureFileCoverRuleCount(keyword, supplyName);
        if (count > 0){
            return true;
        }
        return false;
    }

    /**
     * 新增保单遮盖处理
     *
     * @param insureFileCoverRule
     * @return
     */
    @Override
    public int insertInsureFileCoverRule(InsureFileCoverRule insureFileCoverRule) {
        return insureFileCoverRuleMapper.insertInsureFileCoverRule(insureFileCoverRule);
    }

    /**
     * 校验关键字是否唯一
     *
     * @param insureFileCoverRule
     * @return
     */
    @Override
    public boolean checkKeywordUnique2(InsureFileCoverRule insureFileCoverRule) {
        InsureFileCoverRule old = insureFileCoverRuleMapper.selectInsureFileCoverRule(insureFileCoverRule);
        if (old != null && !insureFileCoverRule.getId().equals(old.getId())){
            return true;
        }
        return false;
    }

    /**
     * 修改保单遮盖处理
     *
     * @param insureFileCoverRule
     * @return
     */
    @Override
    public int updateInsureFileCoverRule(InsureFileCoverRule insureFileCoverRule) {
        return insureFileCoverRuleMapper.updateInsureFileCoverRule(insureFileCoverRule);
    }

    /**
     * 删除保单遮盖处理
     *
     * @param id
     * @return
     */
    @Override
    public int deleteInsureFileCoverRuleById(Long id) {
        return insureFileCoverRuleMapper.deleteInsureFileCoverRuleById(id);
    }

    /**
     * 保单遮盖处理
     *
     * @param multipartFile
     * @param supplyName
     * @return
     */
    @Override
    public String pdfCover(MultipartFile multipartFile, String supplyName) {
        long begin = System.currentTimeMillis();
        log.info("开始处理保单遮盖处理-------------");
        //遮盖后的保单url
        String pdfCoverUrl = null;
        try {
            //文件名称（1.pdf）
            String fileName = multipartFile.getOriginalFilename();
            if (fileName == null || !fileName.endsWith(".pdf")) {
                throw new UtilException("文件不是pdf文件，请检查");
            }
            String basePath = SupplyConfig.getProfile() + IdUtils.fastSimpleUUID();
            //MultipartFile 转换为file的存储路径
            String sourcePath = basePath + "/" + fileName;
            File file = FileUtils.multiPartFileToFile(multipartFile, sourcePath);
            if (file == null || !file.isFile() || file.length() == 0){
                throw new UtilException("文件转换异常");
            }
            //保单遮盖后的文件路径
            String targetPath = basePath + "/cover/" + fileName;
            //String sourcePath = "src/main/resources/file/06020400142112062023000004.pdf";
            //String pdfCoverPath = "src/main/resources/file/06020400142112062023000004_2.pdf";
            //根据供应商查询该供应商保单内容的遮盖规则
            List<InsureFileCoverRule> insureFileCoverRuleList = insureFileCoverRuleMapper.selectInsureFileCoverRuleListBySupplyName(supplyName);
            log.info("供应商：{}，查询的保单遮盖规则：{}", supplyName, insureFileCoverRuleList);
            if (StringUtils.isEmpty(insureFileCoverRuleList)){
                throw new UtilException("供应商：" + supplyName + "未配置保单遮盖规则！");
            }
            Map<String, InsureFileCoverRule> ruleMap = insureFileCoverRuleList.stream().collect(Collectors.toMap(InsureFileCoverRule::getKeyword, e -> e, (k1, k2) -> k2));
            Map<Integer, List<OverArea>> overAreaListMap;
            //创建文件路径
            PdfWaterUtils.createFilePath(targetPath);
            //关键字的坐标集合
            overAreaListMap = PdfCoverUtils.getKeywordPosition(sourcePath, insureFileCoverRuleList);
            PdfCoverUtils.pdfCover(sourcePath, targetPath, overAreaListMap, null, ruleMap);
            log.info("保单遮盖处理完成，上传到oss -------------------");
            //上传到oss
            fileName = fileName.substring(fileName.lastIndexOf("."));
            String path = FileUtils.getPath() + IdUtils.fastSimpleUUID() + fileName;
            OssUtil.ins().uploadFile(path, Files.newInputStream(Paths.get(targetPath)));
            pdfCoverUrl = OssUtil.ins().getFileUrl(path);
            //删除文件
            FileUtils.deleteDirectory(new File(basePath));
        } catch (IOException e) {
            log.error("文件内容遮盖异常：", e);
            throw new UtilException("系统异常：" + e.getMessage());
        }
        log.info("保单遮盖处理完成-------------,总耗时：{}", System.currentTimeMillis() - begin);
        return pdfCoverUrl;
    }
}
